//
//  MSUserDetailViewController.m
//  MSJD
//
//  Created by 箭军刘 on 2018/12/10.
//  Copyright © 2018 xiangbo. All rights reserved.
//

#import "MSUserDetailViewController.h"

#import "MSUserEditNameController.h"
#import "TZImagePickerController.h"

#import "MSUserCenterCell.h"

#import "MSUserCenterDataSource.h"
#import "MSUploadImageUtils.h"

@interface MSUserDetailViewController ()<TZImagePickerControllerDelegate>

@property (nonatomic, copy) NSString *iconUrl; // 新的图片URL

@end

@implementation MSUserDetailViewController

+ (instancetype)loadUserDetailViewController {
    MSUserDetailViewController *userDetailVC = [[MSUserDetailViewController alloc] init];
    return userDetailVC;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"个人资料";
    
    [self.tableView registerNib:[UINib nibWithNibName:@"MSUserCenterCell" bundle:nil] forCellReuseIdentifier:@"MSUserCenterCell"];
    
    self.customDataSource = @[@"头像", @"昵称"];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.tableView reloadData];
}

#pragma mark - TZImagePickerControllerDelegate

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto infos:(NSArray<NSDictionary *> *)infos {
    UIImage *image = [photos firstObject];
    //    self.icon.image = image;
    NSLog(@"image:%@", image);
    // 获取凭证
    _WEAKSELF
    [MSUserCenterDataSource queryUploadImageConfigWithSuccess:^(NSDictionary * _Nonnull responseInfo) {
        if ([MSSafeObject isNull:responseInfo]) {
            return ;
        }
        [weakSelf handleImage:responseInfo image:image];
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD showToastWithMessage:@"图像上传失败，请稍后再试！" toView:weakSelf.view];
    }];
}

- (void)handleImage:(NSDictionary *)response image:(UIImage *)image {
    _WEAKSELF
    [MBProgressHUD showMessage:@"图片上传中"];
    [MSUploadImageUtils uploadImage:image withImageUpload:response bucketName:@"" resultBlock:^(NSDictionary *responseInfo) {
        dispatch_sync(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUD];
            if ([[MSSafeObject stringInfo:responseInfo[@"result"]] isEqualToString:@"1"]) {
                [weakSelf changeUserIcon:responseInfo[@"photoname"]];
            } else {
                [MBProgressHUD showToastWithMessage:@"图片上传失败！" toView:weakSelf.view];
            }
        });
    }];
}

#pragma mark - Reset Method

- (UITableViewCell *)loadCustomCellWithTableView:(UITableView *)tableView Index:(NSIndexPath *)indexPath {
    MSUserCenterCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MSUserCenterCell"];
    if (self.customDataSource.count > indexPath.row) {
        [cell refreshUserDetailCellWithTitle:self.customDataSource[indexPath.row] index:indexPath.row];
    }
    return cell;
}

- (void)didSelectTableView:(UITableView *)tableView indexPath:(NSIndexPath *)indexPath {
    switch (indexPath.row) {
        case 0:
        { // 切换头像
            [self chooseUserIcon];
        }
            break;
        case 1:
        { // 修改昵称
            [self changeUserName];
        }
            break;
        case 2:
        { // 修改性别
            [self changeUserGender];
        }
            break;
        default:
            break;
    }
    
}
/** 计算cell的高度 */
- (CGFloat)caculateCellHeightWithIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 0) {
        return 70;
    }
    return 50;
}

#pragma mark - Private Method
/** 选择用户头像 */
- (void)chooseUserIcon {
    
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
    imagePickerVc.allowTakePicture = YES;
    imagePickerVc.allowTakeVideo = NO;
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.allowCrop = YES;
//    imagePickerVc.allowPickingGif = YES;
    imagePickerVc.barItemTextColor = [UIColor blackColor];
    imagePickerVc.iconThemeColor = [UIColor orangeColor];
    imagePickerVc.oKButtonTitleColorNormal = [UIColor greenColor];
    imagePickerVc.oKButtonTitleColorDisabled = [UIColor blueColor];
    imagePickerVc.showSelectedIndex = YES;
    imagePickerVc.statusBarStyle = UIStatusBarStyleLightContent;
    imagePickerVc.cropRect = CGRectMake(0, (MS_SCREEN_HEIGHT - MS_SCREEN_WIDTH) / 2.0, MS_SCREEN_WIDTH, MS_SCREEN_WIDTH);
    [[UIViewController currentViewController] presentViewController:imagePickerVc animated:YES completion:nil];
}
/** 修改用户昵称 */
- (void)changeUserName {
    MSUserEditNameController *userEditNameVC = [MSUserEditNameController loadUserEditNameController];
    [self.navigationController pushViewController:userEditNameVC animated:YES];
}
/** 修改用户性别 */
- (void)changeUserGender {
    NSArray *genderList = @[@"男", @"女"];
    _WEAKSELF
    [self showActionSheetWithTitle:nil message:nil buttonTitles:genderList cancelButton:@"取消" clickView:nil confirmClickBlock:^(NSInteger buttonIndex) {
        MSUser *loginUser = [UserAccesser loadAccount];
        loginUser.gender = [NSNumber numberWithInteger:(buttonIndex + 1)];
        MSUserCenterCell *genderCell = [weakSelf.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:2 inSection:0]];
        [genderCell refreshUserDetailCellWithTitle:weakSelf.customDataSource[2] index:2];
    } cancelBlock:nil];
}
/** 修改用户头像 */
- (void)changeUserIcon:(NSString *)iconUrl {
    if ([MSSafeObject isNull:iconUrl]) {
        [MBProgressHUD showToastWithMessage:@"图片上传失败" toView:self.view];
        return;
    }
    _WEAKSELF
    [MSUserCenterDataSource modifyUserInfoWithAvatar:iconUrl userName:[UserAccesser loadAccount].username gender:0 success:^(NSDictionary *responseInfo) {
        MSUser *loginUser = [UserAccesser loadAccount];
        loginUser.avatar = iconUrl;
        [UserAccesser saveAccountToLocal:loginUser];
        [weakSelf.tableView reloadData];
        [MBProgressHUD showToastWithMessage:@"修改成功" toView:weakSelf.view];
    } failure:^(NSError *error) {
        NSString *errorMsg = error.localizedDescription?:@"修改用户头像失败";
        [MBProgressHUD showToastWithMessage:errorMsg toView:weakSelf.view];
    }];
}

#pragma mark -  Memory Method

- (void)dealloc {
    NSLog(@"%s", __func__);
}

@end
